// 进行登录请求
function login() {
    if (!loginValidate()) {
        return false;
    }
    $.ajax({
        type: "POST",
        url: "/login",
        data: {userName: $("#username").val(), password: $("#password").val()},
        dataType: "json",
        success: function (response) {
            if (undefined !== response && response.success === true) {
                window.location.href = '/';
                localStorage.setItem("id", response.data.user.id);
            } else {
                window.location.href = '/login';
            }
        }
    })
}

// 校验用户名和密码，同时有效的话，并将密码进行MD5转码
function loginValidate() {
    var msg;
    var username = $('#username');
    var password = $('#password');
    if ($.trim(username.val()).length === 0) {
        msg = "用户名不能为空";
    } else if ($.trim(password.val()).length === 0) {
        msg = "密码不能为空";
    }
    if (msg && msg.length > 0) {
        layer.alert(msg, {icon: 7});
        return false;
    } else {
        var mm = $.trim(password.val());
        var md5value = $.md5(mm);
        password.val(md5value);
        return true;
    }
}

// 设置全局监听事件
document.onkeydown = function (ev) {
    var e = ev || window.ev || arguments.callee.caller.arguments[0] || e.which;
    if (e && e.keyCode === 13) {
        login();
    }
};